import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();

// 获取客户面单统计
router.get("/customer/:customerId", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { customerId } = req.params;

    // 统计充值数量
    const rechargeStats = await db
      .collection("waybill_recharge")
      .aggregate([
        { $match: { customerId: new ObjectId(customerId) } },
        {
          $group: {
            _id: null,
            totalRecharged: { $sum: "$quantity" },
          },
        },
      ])
      .toArray();

    // 统计使用数量（这里假设有一个使用记录表，如果没有则默认为0）
    const usageStats = await db
      .collection("waybill_usage")
      .aggregate([
        { $match: { customerId: new ObjectId(customerId) } },
        {
          $group: {
            _id: null,
            totalUsed: { $sum: "$quantity" },
          },
        },
      ])
      .toArray();

    const totalRecharged = rechargeStats[0]?.totalRecharged || 0;
    const totalUsed = usageStats[0]?.totalUsed || 0;
    const remaining = Math.max(0, totalRecharged - totalUsed);

    res.json({
      totalRecharged,
      totalUsed,
      remaining,
    });
  } catch (error) {
    console.error("获取客户面单统计失败:", error);
    res.status(500).json({ error: "获取客户面单统计失败" });
  }
});

// 获取店铺快递公司面单统计
router.get("/shop/:shopId", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { shopId } = req.params;

    // 获取店铺信息
    const shop = await db
      .collection("shops")
      .findOne({ _id: new ObjectId(shopId) });
    if (!shop) {
      return res.status(404).json({ error: "店铺不存在" });
    }

    const stats = {};

    // 为每个快递公司统计面单数量
    for (const expressCompany of shop.expressCompanies) {
      // 统计充值数量
      const rechargeStats = await db
        .collection("waybill_recharge")
        .aggregate([
          {
            $match: {
              shopId: new ObjectId(shopId),
              expressCompany: expressCompany,
            },
          },
          {
            $group: {
              _id: null,
              totalRecharged: { $sum: "$quantity" },
            },
          },
        ])
        .toArray();

      // 统计使用数量
      const usageStats = await db
        .collection("waybill_usage")
        .aggregate([
          {
            $match: {
              shopId: new ObjectId(shopId),
              expressCompany: expressCompany,
            },
          },
          {
            $group: {
              _id: null,
              totalUsed: { $sum: "$quantity" },
            },
          },
        ])
        .toArray();

      const totalRecharged = rechargeStats[0]?.totalRecharged || 0;
      const totalUsed = usageStats[0]?.totalUsed || 0;
      const remaining = Math.max(0, totalRecharged - totalUsed);

      stats[expressCompany] = {
        totalRecharged,
        totalUsed,
        remaining,
      };
    }

    res.json(stats);
  } catch (error) {
    console.error("获取店铺面单统计失败:", error);
    res.status(500).json({ error: "获取店铺面单统计失败" });
  }
});

// 批量获取客户面单统计
router.post("/batch-customers", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { customerIds } = req.body;

    if (!Array.isArray(customerIds) || customerIds.length === 0) {
      return res.json({});
    }

    const objectIds = customerIds.map((id) => new ObjectId(id));
    const stats = {};

    // 批量统计充值数量
    const rechargeStats = await db
      .collection("waybill_recharge")
      .aggregate([
        { $match: { customerId: { $in: objectIds } } },
        {
          $group: {
            _id: "$customerId",
            totalRecharged: { $sum: "$quantity" },
          },
        },
      ])
      .toArray();

    // 批量统计使用数量
    const usageStats = await db
      .collection("waybill_usage")
      .aggregate([
        { $match: { customerId: { $in: objectIds } } },
        {
          $group: {
            _id: "$customerId",
            totalUsed: { $sum: "$quantity" },
          },
        },
      ])
      .toArray();

    // 组装统计结果
    customerIds.forEach((customerId) => {
      const rechargeData = rechargeStats.find(
        (item) => item._id.toString() === customerId
      );
      const usageData = usageStats.find(
        (item) => item._id.toString() === customerId
      );

      const totalRecharged = rechargeData?.totalRecharged || 0;
      const totalUsed = usageData?.totalUsed || 0;
      const remaining = Math.max(0, totalRecharged - totalUsed);

      stats[customerId] = {
        totalRecharged,
        totalUsed,
        remaining,
      };
    });

    res.json(stats);
  } catch (error) {
    console.error("批量获取客户面单统计失败:", error);
    res.status(500).json({ error: "批量获取客户面单统计失败" });
  }
});

// 批量获取店铺面单统计
router.post("/batch-shops", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { shopIds } = req.body;

    if (!Array.isArray(shopIds) || shopIds.length === 0) {
      return res.json({});
    }

    const objectIds = shopIds.map((id) => new ObjectId(id));
    const stats = {};

    // 获取所有店铺信息
    const shops = await db
      .collection("shops")
      .find({ _id: { $in: objectIds } })
      .toArray();

    for (const shop of shops) {
      const shopStats = {};

      // 为每个快递公司统计面单数量
      for (const expressCompany of shop.expressCompanies) {
        // 统计充值数量
        const rechargeStats = await db
          .collection("waybill_recharge")
          .aggregate([
            {
              $match: {
                shopId: shop._id,
                expressCompany: expressCompany,
              },
            },
            {
              $group: {
                _id: null,
                totalRecharged: { $sum: "$quantity" },
              },
            },
          ])
          .toArray();

        // 统计使用数量
        const usageStats = await db
          .collection("waybill_usage")
          .aggregate([
            {
              $match: {
                shopId: shop._id,
                expressCompany: expressCompany,
              },
            },
            {
              $group: {
                _id: null,
                totalUsed: { $sum: "$quantity" },
              },
            },
          ])
          .toArray();

        const totalRecharged = rechargeStats[0]?.totalRecharged || 0;
        const totalUsed = usageStats[0]?.totalUsed || 0;
        const remaining = Math.max(0, totalRecharged - totalUsed);

        shopStats[expressCompany] = {
          totalRecharged,
          totalUsed,
          remaining,
        };
      }

      stats[shop._id.toString()] = shopStats;
    }

    res.json(stats);
  } catch (error) {
    console.error("批量获取店铺面单统计失败:", error);
    res.status(500).json({ error: "批量获取店铺面单统计失败" });
  }
});

export default router;
